/**
 * Decide the mode of the sound
 * @author Di
 * @date April 21st, 2011
 */

package test.android;

import java.util.Arrays;

public class ModeController {
	private static final float BLANK = -999;
	private static final int LOW = 0;
	private static final int HIGH = 1;
	private static final int SPLASH = 2;	
	private int size = 100; //default size of buffer
	private float[] bufferX;
	private float[] bufferY;
	private float[] bufferZ;
	private int position = 0;
	int count =0;

	public ModeController() {
		bufferX = new float[size];
		bufferY = new float[size];
		bufferZ = new float[size];
		clear();
	}

	private void clear() {
		Arrays.fill(bufferX, BLANK);
		Arrays.fill(bufferY, BLANK);
		Arrays.fill(bufferZ, BLANK);
	}

	public float getMedian(float values[]) {
		int len = values.length;
		float[] tmp = new float[len];		
		for (int i = 0; i < len; i++) {
			if (tmp[i]!= BLANK){
				tmp[i] = Math.abs(values[i]);
			}
		}
		Arrays.sort(tmp);
		int first = 0;
		for (int i = 0; i < len; i++) {
			first = i;
			if (tmp[i] != BLANK)
				break;
		}
		return Math.abs(tmp[(len - first) / 2 + first]);
	}
	
	private int findMax(float a, float b, float c) {
		float value[] = { a, b, c };
		Arrays.sort(value);
		if (value[2] == a) {
			return 0;
		} else if (value[0] == b) {
			return 1;
		} else
			return 2;
	}	

	public boolean add(float values[]) {
		bufferX[position] = values[0];
		bufferY[position] = values[1];
		bufferZ[position] = values[2];
		if (count%4 ==0 ){
		//System.out.println(values[0]);
		//System.out.println(values[1]);
		//System.out.println(values[2]);
		//System.out.println("---");
		
		}
		count++;
		
		if (size - 1 == position) {
			position = 0;
			return false; // full, start from the beginning
		}
		position++;
		return true; // empty
	}

	public int getMode(float x, float y, float z) {
		//high pass filter
		float valueX = Math.abs(x) - getMedian(bufferX);
		float valueY = Math.abs(y) - getMedian(bufferY);
		float valueZ = Math.abs(z) - getMedian(bufferZ);
		System.out.println(getMedian(bufferY));
		System.out.println(valueZ);
	    System.out.println("---");
		int result = findMax(valueZ + valueY, valueX + valueZ, valueX + valueY);		
		switch (result) {
		case 0:
			return LOW;
		case 1:
			return HIGH;
		case 2:
			return SPLASH;
		default:
			return -1;
		}
	}
}
